package cn.kgc.kgde.bookstore.controller;

import cn.kgc.kgde.bookstore.entity.ResultInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author xiaodai
 * @create 2022-04-25 16:08
 */
public class CheckUserLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object admin = request.getSession().getAttribute( "admin" );
        Object user = request.getSession().getAttribute( "user" );
        if(admin==null && user==null){//没有登录
            //响应登录失败，重新登录
            response.setCharacterEncoding( "utf-8" );
            response.setContentType("application/json");
            PrintWriter out = null;
            try {
                out=response.getWriter();
                ResultInfo resultInfo = new ResultInfo( 401,"登录异常,请重新登录");
                ObjectMapper objectMapper=new ObjectMapper();
                String valueAsString = objectMapper.writeValueAsString( resultInfo );
                out.print( valueAsString );
            }finally {
                if (out!=null){
                    out.flush();
                    out.close();
                }
            }
            return false;
        }
        return true;
    }
}
